<?php

/**
 * 违规合同仓库
 * @author yuzy 2015-5-7
 */

namespace common\repositories\myhtsq;

use common\repositories\BaseRepository;
use common\entities\myhtsq\ViolatedContractEntity;
use common\error\ErrorCode;
use common\support\PageParam;
use common\support\Helper;
use common\support\StringHelper;
use Exception;

class ViolatedContractRepository extends BaseRepository {

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 违规合同列表
     * @param \common\support\PageParam $pageParam 分页参数
     * @param string $areaId 地区id
     * @param array $keyword 关键字
     * @return array
     */
    public static function getViolatedContractList($pageParam, $areaId, $keyword) {        
        // todo：所属区域未取值
        $skip = $pageParam->getSkipByPageParam();
        $query = ViolatedContractEntity::find();
        $query->select("myscrm_violated_contract.*,principal.UserName as principal_name,approver.UserName as approver_name,"
                        ."myscrm_violated_category.category_name,myscrm_violated_littler_category.littler_category_name,"
                        ."myscrm_contract_manage.customer_name,businessunit.BUName as area_name");
        
        //区域id
        if (!empty($areaId)) {
            $query->andWhere(['myscrm_contract_manage.area_id' => $areaId]);
        }
        
        // 关键字过滤
        if (!empty($keyword)) {
            $query->andWhere(['or', ['like', 'myscrm_contract_manage.customer_name', $keyword], ['like', 'myscrm_violated_contract.contract_code', $keyword]]);
        }

        $query->leftJoin('myscrm_contract_manage', 'myscrm_contract_manage.contract_code = myscrm_violated_contract.contract_code')
                ->leftJoin('myscrm_erp_user principal', 'principal.userguid = myscrm_violated_contract.violated_principal')
                ->leftJoin('myscrm_erp_user approver', 'approver.userguid = myscrm_violated_contract.approver')
                ->leftJoin('myscrm_erp_business_unit businessunit', 'businessunit.BUGUID = myscrm_contract_manage.area_id')
                ->leftJoin('myscrm_violated_category', 'myscrm_violated_category.violated_category_id = myscrm_violated_contract.violated_category_id')
                ->leftJoin('myscrm_violated_littler_category', 'myscrm_violated_littler_category.violated_littler_category_id = myscrm_violated_contract.violated_littler_category_id')
                ->offset($skip)
                ->limit($pageParam->pageSize)
                ->orderBy([$pageParam->sortBy => $pageParam->sortAsc]);

        $result = $query->asArray()->all(); //这里必须asArray，否则无法获取关联字段的属性值

        // 统计
        $totalResult = ViolatedContractEntity::find();
        if (!empty($areaId)) {
            $totalResult->andWhere(['myscrm_contract_manage.area_id' => $areaId]);
        }
        if (!empty($keyword)) {
            $totalResult->andWhere(['or', ['like', 'myscrm_contract_manage.customer_name', $keyword], ['like', 'myscrm_violated_contract.contract_code', $keyword]]);
        }
        $totalResult->leftJoin('myscrm_contract_manage', 'myscrm_contract_manage.contract_code = myscrm_violated_contract.contract_code');
        
        $total = $totalResult->count();

        $pageResult = Helper::setPageResult($total, $result);
        return $pageResult;
    }

    /**
     * 获取违规合同实体信息
     * @param string $contractId
     * @return \common\entities\myhtsq\ViolatedContractEntity
     */
    public static function getViolatedContractInfo($contractId) {
        return ViolatedContractEntity::find()
            ->select('myscrm_violated_contract.*,principal.username as principal_name,approver.username as approver_name,myscrm_violated_category.category_name,myscrm_violated_littler_category.littler_category_name')
            ->where(['violated_contract_id'=>$contractId])
            ->leftJoin('myscrm_erp_user principal', 'principal.userguid = myscrm_violated_contract.violated_principal')
            ->leftJoin('myscrm_erp_user approver', 'approver.userguid = myscrm_violated_contract.approver')
            ->leftJoin('myscrm_violated_category', 'myscrm_violated_category.violated_category_id = myscrm_violated_contract.violated_category_id')
            ->leftJoin('myscrm_violated_littler_category', 'myscrm_violated_littler_category.violated_littler_category_id = myscrm_violated_contract.violated_littler_category_id')
            ->asArray()
            ->one();
    }
    
    /**
     * 新增违规合同
     * @param \common\models\myhtsq\ViolatedContractModel $contractModel
     * @return boolean|string 失败返回false，成功返回新增的违规合同Id
     */
    public function addViolatedContract($contractModel) {
        try {
            $entity = new ViolatedContractEntity();
            $entity->setAttributes($contractModel->attributes);
            $entity->violated_contract_id = StringHelper::uuid();
            $result = $entity->save();
            if ($result === FALSE) {
//                $error = $entity->firstErrorMessage;
                return $this->setAndReturn(ErrorCode::ERR_VIOLATED_CONTRACT_SAVE_FAIL);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return $this->setAndReturn(ErrorCode::ERR_VIOLATED_CONTRACT_SAVE_FAIL, (string) $ex);
        }
    }

    /**
     * 更新违规合同
     * @param \common\models\myhtsq\ViolatedContractModel $contractModel
     * @return boolean|string 失败返回false，成功返回编辑的违规合同Id
     */
    public function updateViolatedContract($contractModel) {
        try {
            $entity = ViolatedContractRepository::getViolatedContractById($contractModel->violated_contract_id);
            if (is_null($entity)) {
                return $this->setAndReturn(ErrorCode::ERR_VIOLATED_CONTRACT_SAVE_FAIL);
            }   
            $entity->setAttributes($contractModel->toArray());              
            $result = $entity->update();
            if ($result === FALSE) {
                // todo:无法记录具体错误，难以排错
//                $error = $entity->firstErrorMessage;
                return $this->setAndReturn(ErrorCode::ERR_VIOLATED_CONTRACT_SAVE_FAIL);
            } else {
                return $entity->violated_contract_id;
            }
        } catch (Exception $ex) {
            return $this->setAndReturn(ErrorCode::ERR_VIOLATED_CONTRACT_SAVE_FAIL, (string) $ex);
        }
    }

    /**
     * 根据Id获取违规合同
     * @param type $contractId
     * @return \common\entities\myhtsq\ViolatedContractEntity
     */
    public static function getViolatedContractById($contractId) {
        return ViolatedContractEntity::findOne(['violated_contract_id' => $contractId]);
    }

}
